package com.example.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.example.model.Area;
import com.example.service.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhq
 * @since 2025-01-08
 */
@RestController
@RequestMapping("/area")
public class AreaController {

    @Autowired
    private IAreaService areaService;

    @GetMapping("/getAreaTree")
    public List<Tree<Long>> getAreaTree(){

        List<Area> areaList = areaService.list();
        List<Tree<Long>> trees = buildAreaTree(areaList);
        return trees;

    }


    private List<Tree<Long>> buildAreaTree(List<Area> list){
        TreeNodeConfig config = new TreeNodeConfig();
        config.setIdKey("id");
        config.setParentIdKey("pid");
        List<Tree<Long>> treeList = TreeUtil.build(list, 0L, config, (node, tree) -> {
            tree.setId(node.getAreaId());
            tree.setParentId(node.getParentAreaId() == null ? 0L : node.getParentAreaId());
            tree.setName(node.getAreaName());
//            tree.putExtra("code", node.getAreaCode());  putExtra方法可以在树结构的节点里面加入其他字段
        });
        return treeList;
    }



}
